package com.csp.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author:chengsp
 * @createTime:2019/8/22 12:57
 */
public class DBUtil {
    private static final String DRIVERCLASS;
    private static final String URL;
    private static final String USERNAME;
    private static final String PASSWORD;

    static {
        // 从配置文件中加载数据
        DRIVERCLASS = "com.mysql.cj.jdbc.Driver";
        URL = "jdbc:mysql://47.103.3.1:3306/seckill?useSSL=false&characterEncoding=UTF-8";
        USERNAME = "root";
        PASSWORD = "yourpassword";
    }

    static {
        // 1.注册驱动
        try {
            Class.forName(DRIVERCLASS);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }

    public static Connection getConnection() {
        // 2.获取连接对象Connection
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    /**
     * 关闭连接
     *
     * @param con
     * @throws SQLException
     */
    public static void closeConnection(Connection con) throws SQLException {
        if (con != null) {
            con.close();
        }
    }

    public static void closeStatement(Statement st) throws SQLException {
        if (st != null) {
            st.close();
        }
    }

    public static void closeResultSet(ResultSet rs) throws SQLException {
        if (rs != null) {
            rs.close();
        }
    }
}
